
<template>
  <main class="addUser_box center">
    <div class="username">
      用户名: <input v-model="commitObj.username" placeholder="(长度大于四)"/>
    </div>
    <div class="pass">
      密 码:  <input v-model="commitObj.pass" placeholder="(长度大于四)"/>
    </div>
    <div class="num">
      金币数: 
       <input type="number"
        v-model="commitObj.num"/>
    </div>
    <div class="level">
      用户等级:  
      <select class="level_sel" v-model="commitObj.level">
        <option v-for="it in [1, 2, 3]">{{ it }}</option>  
      </select>
    </div>
    <div class="add_btn">
      <button @click="addUser">添加</button>
    </div>
  </main>
</template>

<script setup>
import {ref} from 'vue'
import {addUserReq} from '../api/index.js'
import {useStore} from "vuex"
import {useRouter} from 'vue-router'
const store = useStore()
const router = useRouter()
const commitObj = ref({
  username: '',
  pass:'',
  num:0,
  level:1,
  score:1
})
const isNull = (str) => {
  return !str || str == "";
}
const addUser = () => {
  if (isNull(commitObj.value.name) || isNull(commitObj.value.pass)
  || commitObj.value.username.length < 4 || commitObj.value.pass.length < 4){
    alert('用户名或密码长度必须大于4')
    return;
  }
  let {token} = store.state.user;
  let res = addUserReq(token, {
    name: commitObj.value.username,
    password:commitObj.value.pass,
    level:commitObj.value.level,
    score:commitObj.value.num
  });
  res.then((resp) => {
    console.log('respp', resp);
    let {data } = resp;
    if (data.code == 200) {
      alert('添加成功')
      store.dispatch('addUser', data.resp_data)
      // 返回用户列表
      router.push({
        path: '/main/userList'
      })
    }else{
      alert('添加失败')
    }
  }).catch(err => {
    console.log(err);
  })
}
</script>

<style scoped>
.addUser_box{
  width: 25%;
  height: 40%;
  margin-top: 130px;
  border: 1px solid black;
  padding: 30px;
  box-sizing: border-box;
}
.addUser_box >div {
  margin-bottom: 10px;
}
.level_sel{
  width: 62%;
}
</style>
  